package com.zlx.store.user.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zlx.store.common.annotation.SecurityAnno;
import com.zlx.store.common.constant.JWTSecurityKey;
import com.zlx.store.common.constant.LoginSend;
import com.zlx.store.common.constant.SecurityConstant;
import com.zlx.store.common.results.HttpResp;
import com.zlx.store.common.constant.RespCode;
import com.zlx.store.common.util.EmailTool;
import com.zlx.store.common.util.StringTool;
import com.zlx.store.domain.entity.StoreRelateUser;
import com.zlx.store.domain.entity.User;
import com.zlx.store.domain.entity.vo.TokenVO;
import com.zlx.store.domain.vo.UserVo;
import com.zlx.store.user.dao.StoreRelateUserDao;
import com.zlx.store.user.service.UserService;
import io.swagger.annotations.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api("tags=用户的Api接口类")
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    StoreRelateUserDao storeRelateUserDao;

    @GetMapping("logByName")
    public HttpResp logByName(String username, String password) {
        User user = userService.selectUserByName(username);
        return loginJudge(user, password);
    }
//    @GetMapping("logManagerByName")
//    public HttpResp logManagerByName(String username,String password,int role){
//        if (role)
//
//        return HttpResp.httpResp(RespCode.USER_LOGIN_SUCCESS,user,new Date());
//    }

    private HttpResp loginJudge(User user, String password) {
        if (Objects.isNull(user)) {
            return HttpResp.httpResp(RespCode.USER_LOGIN_ERROR_USERNAME_NO_FIND, "用户名不存在", new Date());
        }
        if (!password.equals(user.getUserPassword())) {
            return HttpResp.httpResp(RespCode.USER_LOGIN_ERROR, "用户名或密码错误", new Date());
        }
        List<Long> storeIdList = storeRelateUserDao.selectList(
                        new LambdaQueryWrapper<StoreRelateUser>()
                                .eq(StoreRelateUser::getUserId, user.getUserId())).stream()
                .map(StoreRelateUser::getStoreId).collect(Collectors.toList());
        JWTSigner jwtSigner = JWTSignerUtil.hs256(JWTSecurityKey.SECURITY_KEY.key.getBytes(StandardCharsets.UTF_8));
        String jwt = JWT.create().setSigner(jwtSigner)
                .setPayload("username", user.getUserName())
                .setPayload("userId", user.getUserId())
                .setPayload("userRole", user.getUserRole())
                .setPayload("storeIds", storeIdList)
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 30)).toString();
        TokenVO tokenVO = new TokenVO().build(user,storeIdList);
        redisTemplate.opsForValue().set(jwt,tokenVO,60,TimeUnit.MINUTES);
        return HttpResp.httpResp(RespCode.USER_LOGIN_SUCCESS, jwt, new Date());
    }
    /**
     * 添加店长或管理员
     *
     * @param user
     * @return
     */
    @PostMapping("addManager")
    @ApiOperation(value = "addManager", notes = "添加店长或管理员")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_ADMIN)
    public HttpResp addManager(@RequestBody UserVo user) {
        user.getUser().setUserCreateTime(new Date());
        int result = userService.addUser(user);
        if (result == 0) {
            return HttpResp.httpResp(RespCode.USER_OPERATION_ERROR, "用户名已存在", new Date());
        }
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, result, new Date());
    }

    /**
     * 删除用户,即权限变为3
     *
     * @param id
     * @return
     */
    @PutMapping("deleteUser")
    @ApiOperation(value = "delete", notes = "删除用户")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_ADMIN)
    public HttpResp deleteUser(String id) {
        int result = userService.delUser(Long.parseLong(id));
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, result, new Date());
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("editUser")
    @ApiOperation(value = "edit", notes = "修改用户信息")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_ADMIN)
    public HttpResp editUser(@RequestBody UserVo user) {
        user.getUser().setUserUpdateTime(new Date());
        int result = userService.editUser(user);
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, result, new Date());
    }

    /**
     * 普通用户：显示用户详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("showDetail")
    @ApiOperation(value = "showDetail", notes = "普通用户：显示用户详细信息")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_CUSTOMER)
    public HttpResp showDetail(String id) {
        User user = userService.selectUserById(Long.parseLong(id));
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, user, new Date());
    }

    /**
     * 管理用户：显示用户详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("showManagerDetail")
    @ApiOperation(value = "showManagerDetail", notes = "管理用户：显示用户详细信息")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_CUSTOMER)
    public HttpResp showManagerDetail(String id) {
        UserVo user = userService.selectUserVoById(Long.parseLong(id));
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, user, new Date());
    }

    /**
     * 显示所有用户
     *
     * @param currentPage
     * @param size
     * @return
     */
    @GetMapping("showAllUser")
    @ApiOperation(value = "showAllUser", notes = "显示所有用户")
    @SecurityAnno(roleName = SecurityConstant.USER_ROLE_ADMIN)
    public HttpResp showAllUser(@RequestParam int currentPage, @RequestParam int size, Integer role) {
        IPage<User> users = userService.showAllUser(currentPage, size, role);
        return HttpResp.httpResp(RespCode.USER_OPERATION_SUCCESS, users, new Date());
    }
}
